package Customer;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import model.*;
import supermarket.*;

/**
 *
 * @author aggelos, steve
 */
public class MarketPlacePanel extends javax.swing.JPanel {

    private final DBmanager db;
    private final EntityManager em;
    private final EntityManager ccem;
    private final Customer user;
    public MainForm parent;
    private ShowBasketPanel SB;
    private DefaultTableModel products_model;
    private List<Store> allStores;
    private Store SelectedStore;
    private Purchase purchase;
    private List<Product> StoreProducts;
    private final ArrayList<ProductPurchase> basket;
    private Product SelectedProduct;

    public MarketPlacePanel(DBmanager db, MainForm parent) {
        this.db = db;
        this.em = db.getEm();
        this.ccem = db.getCcem();
        this.parent = parent;
        this.user = parent.GetUser();

        //Φτιάξε την λίστα του καλαθιού αγορών
        this.basket = new ArrayList<ProductPurchase>();
        // Προετοίμασε την καταγραφή της αγοράς
        this.purchase = new Purchase();
        this.purchase.setCustomer(this.user);

        initComponents();
        this.updateStoresCombo();
    }

    public void setShowBasketPanel(ShowBasketPanel SB) {
        this.SB = SB;
    }

    public ShowBasketPanel getShowBasketPanel() {
        return this.SB;
    }

    public Purchase getPurchase() {
        return this.purchase;
    }

    public ArrayList<ProductPurchase> getSelectedProducts() {
        return this.basket;
    }

    public void removeProductPurchase(ProductPurchase pp) {
        this.purchase.getProductPurchaseList().remove(pp);
    }

    public void succesfulTransaction() {
        // Δημιούργησε μια αγορά για αυτόν τον πελάτη σε αυτό το κατάστημα
        Purchase newPurchase = this.db.newPurchase(this.user, this.SelectedStore);

        //Συσχέτισε την αγορά με το κατάστημα και σώστο στην ΒΔ
        this.SelectedStore.getPurchaseList().add(newPurchase);
        this.db.updateStore(this.SelectedStore);

        //Συσχέτισε την αγορά με τον Πελάτη και σώστο στην ΒΔ
        this.user.getPurchaseList().add(newPurchase);
        this.db.updateCustomer(this.user);

        // Σώσε όλα τα αγορασμένα προιόντα του καλαθιού στην Βάση
        // υπολόγισε τοταλς και σώστα στην ΒΔ

        int totalpoints = 0;
        int totalamount = 0;
        float totalprize = 0;
        for (int i = 0; i < this.basket.size(); i++) {
            ProductPurchase pp = this.basket.get(i);
            pp.setPurchaseId(newPurchase);
            newPurchase.getProductPurchaseList().add(this.db.newProductPurchase(pp));
            //Points
            int addition_points = pp.getProductId().getPoints() * pp.getQuantity();
            totalpoints += addition_points;
            //Cost
            float addition_prize = pp.getProductId().getPrice() * pp.getQuantity();
            totalprize += addition_prize;
            //Amount
            totalamount += pp.getQuantity();
        }

        // Βρές αριθμό προιόντων και σώστο την κλάση purchase
        newPurchase.setAmount(totalamount);
        newPurchase.setPointsEarned(totalpoints);
        newPurchase.setDelivery(this.purchase.getDelivery());

        //Σώστα όλα στην Βάση
        this.db.updatePurchase(newPurchase);

        // Δες αν χρησημοποιήθηκαν επιταγές και ακυρωσέ τες
        ArrayList<Checks> ChecksList = this.SB.getUsedChecks();

        for (int i = 0; i < ChecksList.size(); i++) {
            Checks c = ChecksList.get(i);
            c.setValid(false);
            this.db.updateCheck(c);
        }

        //Υπολόγισε νέες επιταγές και πόντους
        int Existing_points = this.user.getAvailablePoints();
        int points = Existing_points + totalpoints;

        if (points > 200) {
            // Δημιούργησε επιταγές και δώστου τους ρέστους πόντους
            while (points > 200) {
                points -= 200;
                Checks cc = this.db.newCheck();
                this.user.getChecksList().add(cc);
                cc.getCustomerList().add(this.user);
            }
            this.user.setAvailablePoints(points);
        } else {
            // Add points and updated customer
            this.user.setAvailablePoints(points);
        }
        // Ενημέρωσε την ΒΔ με τις αλλαγές στον πελάτη
        this.db.updateCustomer(this.user);

        // Ενημέρωσε την Φορμα UserChecks
        this.parent.getUserChecksPanel().showUserChecks();

        // Καθάρισε το σύμπαν
        this.resetPurchase();
    }

    public void setSelectedProduct(Product SelectedProduct) {
        this.SelectedProduct = SelectedProduct;
        if (SelectedProduct == null) {
            this.Selected.setText("");
        } else {
            this.Selected.setText(this.SelectedProduct.getName());
        }
    }

    public void failedTransaction() {
        this.resetPurchase();
    }

    private void resetPurchase() {

        this.combo.setEnabled(true);
        // Καθάρισε ότι σχετίζεται με την αγορά
        this.purchase.getProductPurchaseList().remove(this.basket);
        this.basket.clear();
        this.SelectedProduct = null;
        this.SB.setPurchasedProducts();
        //δείξε αρχικό πάνελ αγορών an den to deixneis idi
        this.parent.ShowjPanel(8);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel4 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        combo = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        b_gotoBasket = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        Selected = new javax.swing.JTextField();
        b_addToBasket = new javax.swing.JButton();

        jPanel4.setBackground(new java.awt.Color(248, 127, 7));
        jPanel4.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jPanel4.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));

        jLabel2.setFont(new java.awt.Font("Ubuntu", 1, 24)); // NOI18N
        jLabel2.setText("Πραγματοποίηση Αγορών");

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 308, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGap(0, 0, 0)
                .addComponent(jLabel2)
                .addGap(0, 0, Short.MAX_VALUE))
        );

        combo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                comboActionPerformed(evt);
            }
        });

        jLabel1.setText("Επιλογή Καταστήματος");

        jTable1.setAutoCreateRowSorter(true);
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null}
            },
            new String [] {
                "Κωδικός", "Όνομα", "Τιμή", "Πόντοι"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setFocusable(false);
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        b_gotoBasket.setText("Μετάβαση στο καλάθι");
        b_gotoBasket.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                b_gotoBasketMouseClicked(evt);
            }
        });

        jLabel3.setText("Επιλεγμένο Προιόν :");

        b_addToBasket.setText("Προσθήκη στο καλάθι");
        b_addToBasket.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                b_addToBasketMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 101, Short.MAX_VALUE)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(combo, javax.swing.GroupLayout.PREFERRED_SIZE, 340, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(5, 5, 5)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addComponent(b_addToBasket, javax.swing.GroupLayout.PREFERRED_SIZE, 198, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(b_gotoBasket))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jScrollPane1)
                                .addGap(2, 2, 2))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(Selected, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE)))))
                .addGap(10, 10, 10))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(combo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(20, 20, 20)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 246, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Selected, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(b_gotoBasket)
                    .addComponent(b_addToBasket))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void comboActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboActionPerformed
        this.setStoreProducts();
    }//GEN-LAST:event_comboActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked

        if (this.jTable1.getSelectedRow() != -1) {
            this.SelectedProduct = this.StoreProducts.get(this.jTable1.getSelectedRow());
            this.Selected.setText(this.SelectedProduct.getName());
        }
    }//GEN-LAST:event_jTable1MouseClicked

    private void b_addToBasketMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_b_addToBasketMouseClicked

        if (this.SelectedProduct != null) {
            // Απενεργοποιησε το combo
            // Αγορές κάνουμε απο ένα μόνο κατάστημα (Παραδοχή)
            this.combo.setEnabled(false);
            //Μόλις ολοκληρωθεί η αγορά , το ξαναφτιάχνουμε
            // και αφού το κατάστημα κλείδωσε το γράφουμε στην Purchase
            this.purchase.setStore(this.SelectedStore);

            // Άνοιγμα του παραθύρου επιβεβαίωσης
            ProductPurchaseForm pp = new ProductPurchaseForm(this.SelectedStore, this.SelectedProduct, this.basket, this);
            pp.setVisible(true);

            // Απενεργοποίησε το τρέχον παράθυρο
            parent.setEnabled(false);

        } else {
            JOptionPane.showMessageDialog(this, "Δεν έχει επιλεχθεί προϊόν!", "Σφάλμα", JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_b_addToBasketMouseClicked

    private void b_gotoBasketMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_b_gotoBasketMouseClicked
        parent.ShowjPanel(9);
    }//GEN-LAST:event_b_gotoBasketMouseClicked
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField Selected;
    private javax.swing.JButton b_addToBasket;
    private javax.swing.JButton b_gotoBasket;
    private javax.swing.JComboBox combo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables

    private void updateStoresCombo() {
        try {
            // Ζήτα την λίστα με τα καταστήματα απο την ΒΔ.
            this.allStores = db.getStoreList();
            //Βάζουμε τα στοιχεία στο Combo
            for (int i = 0; i < this.allStores.size(); i++) {
                this.combo.addItem(this.allStores.get(i).getName());
            }
        } catch (Exception e) {
        }
    }

    private void setStoreProducts() {
        if (this.combo.getSelectedIndex() != -1) {

            this.SelectedStore = (Store) this.allStores.get(this.combo.getSelectedIndex());
            this.StoreProducts = this.SelectedStore.getProductList();
            this.Selected.setText("");

            Object[] columnNames = {"Κωδικός", "Όνομα", "Τιμή", "Πόντοι"};
            products_model = new DefaultTableModel(new Object[0][0], columnNames);

            this.jTable1.setModel(products_model);

            //Βάλε data στον Πίνακα
            for (Product p : StoreProducts) {
                Object[] o = new Object[4];
                o[0] = p.getProductId();
                o[1] = p.getName();
                o[2] = p.getPrice();
                o[3] = p.getPoints();
                products_model.addRow(o);
            }
        }
    }
}
